package br.com.ime.usp.cmep;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpUtils {

	private HttpUtils() { }
	
    // faz um HTTP POST
    // adaptado de http://javacream.blogspot.com.br/2008/04/java-http-get-post.html
    public static String post(String _url, HashMap<String,String> params) throws Exception {
		if(!ConnectionUtils.isConnected())
			throw new Exception("Sem conexão!");
		
		String response = ""; //for reading from remote host
		InputStream in = null; //for posting parameters to remote host
		DataOutputStream out = null;
			
		try {
			// params...
			String line = "";
			for(HashMap.Entry<String,String> entry : params.entrySet()) {
				String field = entry.getKey();
				String data = entry.getValue();
				line += "&" + URLEncoder.encode(field, "UTF-8") + "=" + URLEncoder.encode(data, "UTF-8");
			}
			line = line.substring(1);
			
    		// setup url connection
			URL url = new URL(_url);
			HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
			
			// go go go!
			urlConn.setRequestMethod("POST");
			urlConn.setDoInput(true);
			urlConn.setDoOutput(true);
			urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			out = new DataOutputStream(urlConn.getOutputStream());
			out.writeBytes(line);
			out.flush();
			
			in = urlConn.getInputStream();
			StringBuilder sb = new StringBuilder();
			int i;
			while ((i = in.read()) > -1)
				sb.append((char) i);
			response = sb.toString();
		} catch (UnsupportedEncodingException e) {
			return null;
		}
		catch(IOException e) {
			return null;
		}
		finally {
			if (in != null) {
				try {
					in.close();
				}
				catch (IOException e) {
					return null;
				}
			}
			
			if (out != null) {
				try {
					out.close();
				}
				catch (IOException e) {
					return null;
				}
			}
		}
		
		return response;
    }
	
    
    // faz um HTTP GET
    // inspirado em http://www.vogella.com/articles/AndroidJSON/article.html
    public static String get(String url) throws Exception {
    	return get(url, "UTF-8");
    }
    
    public static String get(String url, String charset) throws Exception{
		if(!ConnectionUtils.isConnected())
			throw new Exception("Sem conexão!");
		
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content, charset));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				return null;
			}
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
		
		return builder.toString();
    }
}
